package com.owc.filter.content;

import com.owc.common.exception.LoginException;
import com.owc.domain.UserExample;
import com.owc.filter.authentication.Authentication;
import com.owc.filter.authentication.AuthenticationImpl;
import org.springframework.lang.NonNull;
import org.springframework.lang.Nullable;

/**
 * @Author Jackies
 * @Date 2019/12/8 11:31
 * @Description Security context holder.
 **/
public class SecurityContextHolder {

    private final static ThreadLocal<SecurityContext> CONTEXT_HOLDER = new ThreadLocal<>();

    private SecurityContextHolder() {
    }

    /**
     * Gets context.
     *
     * @return security context
     */
    @NonNull
    public static SecurityContext getContext() {
        // Get from thread local
        SecurityContext context = CONTEXT_HOLDER.get();
        if (context == null) {
            throw new LoginException();
        }
        return context;
    }

    /**
     * Sets security context.
     *
     * @param context security context
     */
    public static void setContext(@Nullable SecurityContext context) {
        CONTEXT_HOLDER.set(context);
    }

    public static void createTestUser() {
        CONTEXT_HOLDER.set(new SecurityContextImpl(new AuthenticationImpl(new UserDetail(UserExample.defaultUserExample()))));
    }

    /**
     * Clears context.
     */
    public static void clearContext() {
        CONTEXT_HOLDER.remove();
    }

    /**
     * Get current login user detail info.
     * @return User detail model.
     */
    @NonNull
    public static UserDetail getCurrentUser(){
        Authentication authentication = getContext().getAuthentication();
        if(authentication == null){
            throw new LoginException();
        }
        return authentication.getDetail();
    }

    /**
     * Get current login user phone.
     * @return User phone
     */
    public static String getCurrentUserPhone(){
        return getCurrentUser().getUser().getPhone();
    }

    /**
     * Get current login user id.
     * @return User id
     */
    public static Long getCurrentUserId(){
        return getCurrentUser().getUser().getId();
    }

    /**
     * Get current login user name.
     */
    public static String getCurrentUserName(){
        return getCurrentUser().getUser().getUsername();
    }
}
